using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Linq;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces; 

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 安全服务
    /// 提供安全指标统计、威胁管理、设备管理和登录历史等核心安全业务功能
    /// </summary>
    public class SecurityService : ISecurityService
    {
        // 内存数据存储（演示/默认实现，可替换为仓储或外部服务）
        private static readonly List<ThreatDto> _threats = new();
        private static readonly List<DeviceDto> _devices = new();
        private static readonly List<LoginHistoryDto> _loginHistory = new();
        private static readonly List<GeographicLoginDto> _geoLogins = new();

        /// <summary>
        /// 获取安全指标统计数据
        /// </summary>
        /// <returns>安全指标数据传输对象</returns>
        public async Task<SecurityMetricsDto> GetMetricsAsync()
        {
            await Task.CompletedTask;

            var now = DateTime.UtcNow;
            var start = now.AddDays(-7);

            // 活跃用户：最近24小时登录的去重用户数
            var activeUsers = _loginHistory
                .Where(l => l.LoginTime >= now.AddHours(-24))
                .Select(l => l.UserId)
                .Distinct()
                .Count();

            // 失败登录次数：以威胁类型/描述简单匹配（可根据实际规则替换）
            var failedLoginAttempts = _threats.Count(t =>
                t.Type.Equals("FailedLogin", StringComparison.OrdinalIgnoreCase) ||
                t.Description.Contains("失败", StringComparison.OrdinalIgnoreCase));

            var metrics = new SecurityMetricsDto
            {
                ActiveUsers = activeUsers,
                ThreatCount = _threats.Count,
                RiskScore = Math.Max(0, 100 - Math.Min(100, _threats.Count * 3 + failedLoginAttempts * 2)),
                SecurityEventCount = 0, // 如接入安全事件仓储可替换
                FailedLoginAttempts = failedLoginAttempts,
                TrustedDevicesCount = _devices.Count(d => d.IsTrusted),
                DeviceCount = _devices.Count,
                LoginHistoryCount = _loginHistory.Count,
                StartTime = start,
                EndTime = now,
                LastUpdated = now
            };

            return metrics;
        }
        
        /// <summary>
        /// 分页获取威胁信息
        /// </summary>
        public async Task<IEnumerable<ThreatDto>> GetThreatsAsync(string severity, int page = 1, int limit = 10)
        {
            await Task.CompletedTask;
            page = page <= 0 ? 1 : page;
            limit = limit <= 0 ? 10 : limit;

            IEnumerable<ThreatDto> query = _threats;
            if (!string.IsNullOrWhiteSpace(severity))
            {
                query = query.Where(t => string.Equals(t.Severity, severity, StringComparison.OrdinalIgnoreCase));
            }

            return query
                .OrderByDescending(t => t.DetectedAt)
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList();
        }
        
        /// <summary>
        /// 获取地理位置登录记录
        /// </summary>
        public async Task<IEnumerable<GeographicLoginDto>> GetGeographicLoginsAsync(int days = 7)
        {
            await Task.CompletedTask;
            days = days <= 0 ? 7 : days;
            var since = DateTime.UtcNow.AddDays(-days);
            return _geoLogins
                .Where(g => g.LoginTime >= since)
                .OrderByDescending(g => g.LoginTime)
                .ToList();
        }
        
        /// <summary>
        /// 获取设备列表
        /// </summary>
        public async Task<IEnumerable<DeviceDto>> GetDevicesAsync()
        {
            await Task.CompletedTask;
            return _devices.ToList();
        }
        
        /// <summary>
        /// 信任指定设备（长整型标识符版本）
        /// </summary>
        public async Task TrustDeviceAsync(long deviceId)
        {
            await Task.CompletedTask;
            var device = _devices.FirstOrDefault(d => d.Id == deviceId);
            if (device != null)
            {
                device.IsTrusted = true;
            }
            else
            {
                // 若不存在则创建占位设备并信任（可根据业务改为直接返回）
                _devices.Add(new DeviceDto
                {
                    Id = deviceId,
                    Name = $"Device-{deviceId}",
                    Type = "Unknown",
                    IsTrusted = true,
                    LastLoginTime = DateTime.UtcNow
                });
            }
        }

        /// <summary>
        /// 移除指定设备（长整型标识符版本）
        /// </summary>
        public async Task RemoveDeviceAsync(long deviceId)
        {
            await Task.CompletedTask;
            _devices.RemoveAll(d => d.Id == deviceId);
        }
        
        /// <summary>
        /// 分页获取登录历史记录
        /// </summary>
        public async Task<IEnumerable<LoginHistoryDto>> GetLoginHistoryAsync(int page = 1, int limit = 10, string? startDate = null, string? endDate = null)
        {
            await Task.CompletedTask;
            page = page <= 0 ? 1 : page;
            limit = limit <= 0 ? 10 : limit;

            var query = _loginHistory.AsEnumerable();

            if (!string.IsNullOrWhiteSpace(startDate) && DateTime.TryParse(startDate, out var start))
            {
                query = query.Where(x => x.LoginTime >= start);
            }
            if (!string.IsNullOrWhiteSpace(endDate) && DateTime.TryParse(endDate, out var end))
            {
                query = query.Where(x => x.LoginTime <= end);
            }

            return query
                .OrderByDescending(x => x.LoginTime)
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList();
        }
    }
}
